/**
 * Copyright (C) 2016 Hyphenate Inc. All rights reserved.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.km.wskj.itmonitor.pager.im.ui;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.widget.EaseAlertDialog;
import com.km.wskj.itmonitor.R;
import com.km.wskj.itmonitor.http.ZxlGenericsCallback;
import com.km.wskj.itmonitor.model.UserInfo;
import com.km.wskj.itmonitor.pager.im.IMHelper;
import com.zxl.zxlapplibrary.control.UrlControl;
import com.zxl.zxlapplibrary.http.OkHttpUtils;
import com.zxl.zxlapplibrary.util.LogUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import es.dmoral.toasty.Toasty;
import okhttp3.Call;

//添加好友
public class AddContactActivity extends BaseActivity {
    private static final String TAG = "AddContactActivity";

    @BindView(R.id.tool_bar_back)
    ImageView toolBarBack;
    @BindView(R.id.tool_bar_title)
    TextView toolBarTitle;
    @BindView(R.id.tool_bar_right_text)
    TextView toolBarRightText;
    @BindView(R.id.edit_note)
    EditText editNote;
    @BindView(R.id.avatar)
    ImageView avatar;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.indicator)
    Button indicator;
    @BindView(R.id.ll_user)
    RelativeLayout llUser;

    private ProgressDialog progressDialog;
    private UserInfo userInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.em_activity_add_contact);
        ButterKnife.bind(this);

        toolBarTitle.setText("添加好友");
        toolBarBack.setVisibility(View.VISIBLE);
        toolBarRightText.setVisibility(View.VISIBLE);
        toolBarRightText.setText("查找");

        initData();
    }

    private void initData() {

    }

    public void addContact() {
        //不能添加自己
        if (EMClient.getInstance().getCurrentUser().equals(userInfo.username)) {
            new EaseAlertDialog(this, R.string.not_add_myself).show();
            return;
        }
        //查找是否是好友列表的
        if (IMHelper.getInstance().getContactList().containsKey(userInfo.username)) {
            //let the user know the contact already in your contact list
            if (EMClient.getInstance().contactManager().getBlackListUsernames().contains(userInfo.username)) {
                new EaseAlertDialog(this, R.string.user_already_in_contactlist).show();
                return;
            }
            new EaseAlertDialog(this, R.string.This_user_is_already_your_friend).show();
            return;
        }

        progressDialog = new ProgressDialog(this);
        String stri = getResources().getString(R.string.Is_sending_a_request);
        progressDialog.setMessage(stri);
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.show();

        new Thread(new Runnable() {
            public void run() {
                try {
                    //demo use a hardcode reason here, you need let user to input if you like
                    String s = getResources().getString(R.string.Add_a_friend);
                    //参数为要添加的好友的username和添加理由
                    EMClient.getInstance().contactManager().addContact(userInfo.username, s);
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s1 = getResources().getString(R.string.send_successful);
                            Toasty.success(getApplicationContext(), s1, Toast.LENGTH_SHORT, true).show();
                        }
                    });
                } catch (final Exception e) {
                    runOnUiThread(new Runnable() {
                        public void run() {
                            progressDialog.dismiss();
                            String s2 = getResources().getString(R.string.Request_add_buddy_failure);
                            Toast.makeText(getApplicationContext(), s2 + e.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    });
                }
            }
        }).start();
    }

    @OnClick({R.id.tool_bar_back, R.id.tool_bar_right_text, R.id.indicator})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tool_bar_back:
                finish();
                break;
            case R.id.tool_bar_right_text:
                final String phone = editNote.getText().toString();
                if (TextUtils.isEmpty(phone)) {
                    new EaseAlertDialog(this, "输入手机号").show();
                    return;
                }
                findByUser(phone, new ZxlGenericsCallback<List<UserInfo>>() {
                    @Override
                    public void onError(Call call, Exception e, int i) {
                        LogUtils.e(TAG, e);
                    }

                    @Override
                    public void onResponse(List<UserInfo> userInfos, int i) {
                        if (userInfos.size() > 0) {
                            //show the userame and add button if user exist
                            userInfo = userInfos.get(0);
                            llUser.setVisibility(View.VISIBLE);
                            name.setText(userInfo.nickname == null ? userInfo.username : userInfo.nickname);
                            Glide.with(mActivity).load(userInfo.host + userInfo.headImg).into(avatar);

                        } else
                            Toasty.warning(mActivity, "账号不存在", Toast.LENGTH_SHORT, true).show();
                    }
                });
                break;
            case R.id.indicator:
                addContact();
                break;
        }
    }

    public void findByUser(String username, ZxlGenericsCallback callback) {
        OkHttpUtils
                .get()
                .url("http://192.168.1.129:8088/iOPS/api/user/findByTel")
                .addParams("username", username)
                .build()
                .execute(callback);
    }


}
